package com.honghu.villagepost.activity.fragment

import android.graphics.Typeface
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.blankj.utilcode.util.ActivityUtils
import com.google.android.material.appbar.AppBarLayout
import com.honghu.villagepost.MainActivity
import com.honghu.villagepost.R
import com.honghu.villagepost.activity.*
import com.honghu.villagepost.adapter.BaseFragmentStateAdapter
import com.honghu.villagepost.api.ApiService
import com.honghu.villagepost.base.LazyFragment
import com.honghu.villagepost.callback.DialogCallback
import com.honghu.villagepost.callback.LzyResponse
import com.honghu.villagepost.dialog.OrderCityDialog
import com.honghu.villagepost.dialog.OrderSoonDialog
import com.honghu.villagepost.entity.ShopApplyDetail
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.wuhenzhizao.sku.utils.ScreenUtils
import kotlinx.android.synthetic.main.fragment_home.*

class HomeFragment : LazyFragment(), ViewPager.OnPageChangeListener {

    private val tabFragmentList: MutableList<Fragment> = ArrayList()

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_home, container, false)

    override fun lazyInit() {
        val statusBarHeight = ScreenUtils.getStatusBarHeight(activity)
        root_layout.setPadding(0, statusBarHeight, 0, 0)

        fl_search.setOnClickListener {
            ActivityUtils.startActivity(SearchActivity::class.java)
        }

        iv_msg.setOnClickListener {
            ActivityUtils.startActivity(ContactUsActivity::class.java)
        }

        tv_country.setOnClickListener {
            if (activity is MainActivity) {
                (activity as MainActivity).checkTab(MainActivity.TAB_COUNTRY)
            }
        }

        tv_city.setOnClickListener {
            if (activity is MainActivity) {
                (activity as MainActivity).checkTab(MainActivity.TAB_CITY)
            }
        }

        tv_shop_apply.setOnClickListener {
            getShopDetail();
        }

        tv_quickly_send.setOnClickListener {
            ActivityUtils.startActivity(LogisticsOrderSettleActivity::class.java)
        }

        tv_order.setOnClickListener {
            ActivityUtils.startActivity(LogisticsOrderActivity::class.java)
        }
        tv_all.setOnClickListener {
            ActivityUtils.startActivity(LogisticsOrderActivity::class.java)
        }

        tv_loginstics.setOnClickListener {
            ActivityUtils.startActivity(NearSiteActivity::class.java)
        }

        tv_send_order.setOnClickListener {
            val orderSoonDialog = OrderSoonDialog.newInstance()
            orderSoonDialog.show(childFragmentManager)
        }

        tv_address.setOnClickListener {
            val orderSoonDialog = OrderCityDialog.newInstance()
            orderSoonDialog.show(childFragmentManager)
        }

        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
                onRefreshFragment()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

        })

        var mTitles: MutableList<String> = ArrayList()
        mTitles.add("猜你喜欢")
        mTitles.add("附近商家")
        tabFragmentList.add(HomeLikeFragment.newInstance(HomeNearShopFragment.SHOP_TYPE_HOME))
        tabFragmentList.add(HomeNearShopFragment.newInstance(HomeNearShopFragment.SHOP_TYPE_HOME))
        content_vp.setAdapter(BaseFragmentStateAdapter(childFragmentManager, tabFragmentList, mTitles))
        content_vp.addOnPageChangeListener(this)

        to_tv.setOnClickListener {
            content_vp.setCurrentItem(0)
        }

        near_shop_tv.setOnClickListener {
            content_vp.setCurrentItem(1)
        }

        appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, offset: Int) {

                if (offset >= 0) {
                    setEnableRefresh(true)
                } else {
                    setEnableRefresh(false)
                }
            }

        })

        initTabIndicator(0)
    }

    private fun setEnableRefresh(enableRefresh: Boolean) {
        for (fragment in tabFragmentList) {
            if (fragment is HomeLikeFragment) {
                (fragment as HomeLikeFragment).setEnableRefresh(enableRefresh)
            } else if (fragment is HomeNearShopFragment) {
                (fragment as HomeNearShopFragment).setEnableRefresh(enableRefresh)
            }
        }
    }

    private fun onRefreshFragment() {
        if (tabFragmentList != null){
            val fragment = tabFragmentList.get(content_vp.currentItem)
            if (fragment != null){
                if (fragment is HomeLikeFragment) {
                    (fragment as HomeLikeFragment).onAutoRefresh()
                } else if (fragment is HomeNearShopFragment) {
                    (fragment as HomeNearShopFragment).onAutoRefresh()
                }
            }
        }
    }

    private fun getShopDetail() {
        ApiService.getApplyDetail(this, object : DialogCallback<LzyResponse<ShopApplyDetail>>() {
            override fun onSuccess(response: Response<LzyResponse<ShopApplyDetail>>) {
                val data = response.body().data;
                if (data == null) {
                    ActivityUtils.startActivity(ShopProtocolActivity::class.java)
                } else {
                    ShopApplyActivity.startActivity(activity, data);
                }
            }

            override fun onError(response: Response<LzyResponse<ShopApplyDetail>>) {
                if (response != null && TextUtils.equals(response.exception.message, "未申请")) {
                    ActivityUtils.startActivity(ShopProtocolActivity::class.java)
                }else{
                    super.onError(response)
                }
            }
        })

    }

    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    }

    override fun onPageSelected(position: Int) {
        initTabIndicator(position);
    }

    private fun initTabIndicator(position: Int) {
        if (position == 0) {
            to_tv.isSelected = true;
            to_tv.setTypeface(Typeface.DEFAULT_BOLD)
            near_shop_tv.isSelected = false;
            near_shop_tv.setTypeface(Typeface.DEFAULT)
        } else {
            to_tv.isSelected = false;
            to_tv.setTypeface(Typeface.DEFAULT)
            near_shop_tv.isSelected = true;
            near_shop_tv.setTypeface(Typeface.DEFAULT_BOLD)
        }
    }

    override fun onPageScrollStateChanged(state: Int) {
    }

    override fun onDestroyView() {
        content_vp?.removeOnPageChangeListener(this)
        super.onDestroyView()
    }

    fun onFinishRefresh() {
        refreshLayout?.finishRefresh()
    }
}